import Taro, { Component } from "@tarojs/taro";
import { View, Text } from "@tarojs/components";
import { connect } from "@tarojs/redux";
import { AtButton, AtInputNumber, AtAvatar, AtIcon, AtSwitch, AtActionSheet, AtActionSheetItem, AtModal, AtModalContent, AtModalHeader, AtModalAction } from "taro-ui";
import { $Req } from "@utils";
import NP from 'number-precision'
import qs from "qs"
import QR from 'wxmp-qrcode'
import "./index.scss";
import "@components/ShowBox.scss";

const img_goods = "https://bai-tong-fen-xiao.oss-cn-beijing.aliyuncs.com" + "/shopping/order/goods.png";

@connect(
  ({ userModel, orderModel }) => ({
    userModel,
    orderModel,
  }),
  (dispatch) => ({
    userAction: dispatch.userModel,
    orderAction: dispatch.orderModel,
  })
)
export default class Index extends Component {
  config = {
    navigationBarTitleText: "确认订单",
  };

  constructor() {
    super(...arguments);
    this.state = {
      currentTab: 0,
      switchStatus: false,
      orderList: [],
      totalMoney: "0.00",
      totalMoneyCopy: "0.00",
      totalProduct: 0,
      payType: null,
      showPayModel: false,
      showAliPayModel: false,
      aliPayOk: false,
      jfData: {},
      jfFlag: false,
      discountInfo: {},
      bjfDataTotal: [],
      testStatus: false,
      jfProduct: []
    };

  }

  componentDidShow() {
    let ordersNo = Taro.getStorageSync("ordersNo");
    if (ordersNo) {
      return this.syPay(ordersNo)
    }

    let { orderList, totalProduct, source } = this.$router.params;
    let orderListArr = JSON.parse(orderList);
    let totalMoney = '0.00';
    let a = 0;
    orderListArr.map((item, index) => {
      if (item.integral) {
        a += item.integral
      }

      if (item.integral < item.skuCurrPrice) {
        this.state.bjfDataTotal.push(item);
      }

      if (item.integral == item.skuCurrPrice) {
        this.setState({
          testStatus: true
        })
      }

      item.totalJF = a;
      totalMoney = NP.plus(totalMoney, NP.times(item.quantity, item.skuCurrPrice));
    })

    let stsNum = orderListArr.filter(item => item.integralStatus == 1)
    this.state.jfProduct = stsNum;

    if (stsNum.length) {
      totalMoney = 0;
      orderListArr.map(item => {
        totalMoney += item.skuCurrPrice * item.quantity
      })
    }
    console.log(totalMoney, "----totalMoney-----")

    this.setState({
      orderList: orderListArr,
      totalMoney,
      totalProduct,
      aliPayOk: false,
      showAliPayModel: false,
      source,
      jfProduct: this.state.jfProduct,
      bjfDataTotal: this.state.bjfDataTotal
    }, () => {
      var a1 = 0;
      let sts = orderListArr.filter(item => item.integralStatus == 1)
      orderListArr.forEach(item => a1 += (item.integral * item.quantity))

      console.log(totalMoney, "----totalMoney-----")
      if (sts.length) {
        this.setState({
          totalMoneyCopy: totalMoney - a1 == 0 ? totalMoney : totalMoney - a1
        })
      } else {
        this.getUserDiscount();
      }
    })
    let vipFlag = true;
    this.getUserAddress();
    console.log(orderListArr, "----orderListArr----")
    orderListArr.map((item) => {
      if (item.vip * 1 != 1 && vipFlag) {
        this.getJfNum();
        this.setState({
          jfFlag: true
        })
        vipFlag = false;
      }
    })
  }
  //获取打折优惠
  async getUserDiscount() {
    const { totalMoney } = this.state;
    let { code, data } = await $Req({
      type: 'get',
      url: '/user/getUserDiscount',
    });
    this.setState({
      discountInfo: data,
      totalMoneyCopy: NP.times(totalMoney, NP.divide(data.discountRate, 10))
    })
  }

  // 获取地址
  async getUserAddress() {
    let {
      userModel: { userInfo },
      userAction,
    } = this.props;
    let { code, message, data } = await $Req({
      type: "get",
      url: "/indexUser/getShippingAddress",
      data: {
        userId: userInfo.userId
      },
    });
    if (!data) return;

    if (data.length) {
      let a = Taro.getStorageSync("address");
      const [item] = data.filter(el => el.id == a.id);
      const [flag] = data.filter(el => el.defaultFlag == 1);
      if (item) {
        Taro.setStorageSync("address", item);
      } else {
        Taro.setStorageSync("address", flag);
      }
    } else {
      Taro.setStorageSync("address", {})
    }
  }

  async getJfNum() {
    let { data } = await $Req({
      type: "get",
      url: "/indexUser/getUserIntegral",
      data: {}
    });
    if (!data) return;
    this.setState({
      jfData: data
    })
  }

  onSubmit() {
    // 结算
    Taro.redirectTo({
      url: "/pages/order/success/index",
    });
  }

  // 查询支付结果
  async queryPay(orderId, checkoutId, amount) {
    let { data } = await $Req({
      type: "get",
      url: `/pay/queryPay`,
      data: {
        payModel: "MIC_DISTR_PAY_MODEL_NATIVE",
        payType: "MIC_DISTR_PAY_TYPE_ALIPAY",
        orderId,
        checkoutId,
        orderType: 1,
        amount
      }
    });
    if (!data) return;

    if (data.fundBillList && data.fundBillList.length) {
      this.setState({
        aliPayOk: true,
        showPayModel: false
      })
    }
  }

  // 购买产品 获取订单
  async buyGoods() {
    Taro.showToast({
      title: "处理中",
      icon: "loading",
      duration: 3000,
    });

    const {
      userModel: { userInfo },
    } = this.props;

    let { orderList, totalMoneyCopy, totalMoney, payType, switchStatus, jfData, source } = this.state;
    let address = Taro.getStorageSync("address");
    if (!address.id) {
      Taro.showToast({
        title: "请添加地址后再试！",
        icon: "none"
      })

      return false;
    }

    orderList.forEach(el => {
      el.skuDetail = 0;
      if (Object.prototype.toString.call(el.skuImgUrl) == "[object Array]") {
        el.skuImgUrl = el.skuImgUrl.join(",");
        return;
      }
    })

    // 微信混合
    if (switchStatus && payType == 1) {
      payType = 4;
    }

    // 扫码混合
    if (switchStatus && payType == 3) {
      payType = 5;
    }

    orderList.forEach(el => {
      if (el.skuSpecsTypeList) {
        el.skuSpecsTypeList.forEach(item => {
          item.specsList = item.skuSpecsList
          delete item.skuSpecsList;
        })

        el.specsTypeList = el.skuSpecsTypeList;
        delete el.skuSpecsTypeList;
      }
    })

    let postData = {
      payWay: payType,
      userId: userInfo.userId,
      finalAmount: totalMoneyCopy,
      totalAmount: totalMoney,
      originalAmount: totalMoney,
      receiverAddress: address.receiverAddress,
      receiverDistrict: address.receiverDistrict,
      receiverMobile: address.receiverMobile,
      receiverName: address.receiverName,
      skuList: orderList
    };

    if (switchStatus) {
      postData.intergralAmount = jfData.integral;
      if (jfData.integral > 0 && jfData.integral < postData.totalAmount) {
        // postData.payWay = 4;
        // 混合支付
        postData.finalAmount = postData.totalAmount - jfData.integral;
        postData.useIntegral = jfData.integral;
      } else {
        postData.useIntegral = postData.totalAmount;
      }
    }

    let stsNum = orderList.filter(item => item.integralStatus == 1)
    if (stsNum) {
      postData.intergralAmount = totalMoney - totalMoneyCopy;
    }

    if (source == 'cart') {
      postData.createOrderType = 1;
    } else {
      postData.createOrderType = 0;
    }

    let { data } = await $Req({
      type: "POST",
      url: "/order/createOrder",
      data: postData,
    });

    if (!data) return;

    postData.ordersNo = data[0];

    switch (payType) {
      case 1:
        this.getPaySign(data[0], postData.finalAmount, postData);
        break;
      case 2:
        this.getJFPay(data[0], this.state.totalMoneyCopy, postData);
        break;
      case 3:
        this.getNativePaySign(data[0], postData.finalAmount, postData);
        break;
      case 10:
        this.syPay(data[0], postData.finalAmount, postData);
        break;
    }
  }

  // 收益支付
  async syPay(ordersNo, totalMoney, result) {
    const {
      userModel: { userInfo },
    } = this.props;

    // 检查支付密码
    let abc = await $Req({
      type: "get",
      url: "/indexUser/checkHavePayPassword",
      data: { userId: userInfo.userId },
    });
    let payFlag = Taro.getStorageSync("syPay");

    if (abc.code == 200) {
      if (!payFlag) {
        // 有密码
        if (abc.data) {
          Taro.navigateTo({
            url: `/pages/user/payPwd/index?flag=1&price=${this.state.totalMoneyCopy}&ordersNo=${ordersNo}`
          })
          return false;
        }
        // 没密码 
        else {
          Taro.navigateTo({
            url: '/pages/user/payPwd/index'
          })
          return false;
        }
      } else {
        Taro.showLoading({
          title: "支付中..."
        })

        var obj = await $Req({
          type: "post",
          url: `/order/usebenefitPay?ordersNo=${ordersNo}`,
          // data: {
          //   payType: 10,
          //   ordersNo: ordersNo,
          // },
        });
        Taro.removeStorageSync("syPay");
        Taro.removeStorageSync("ordersNo");
        if (obj.code != 200) return;

        Taro.hideLoading();

        Taro.showToast({
          title: "支付成功",
          icon: "none"
        })
        return false;
      }
    }
  }

  // 积分支付
  async getJFPay(ordersNo, totalMoney, result) {
    const {
      userModel: { userInfo },
    } = this.props;
    let { data } = await $Req({
      type: "post",
      url: `/order/useIntegralPay?${qs.stringify({
        ordersNo,
        userId: userInfo.userId,
        useIntegral: totalMoney
      })}`,
    });
    if (!data) return;

    Taro.redirectTo({
      url: "/pages/order/success/index?orderDetails=" + JSON.stringify(result),
    });
  }

  // 支付宝支付签名
  async getNativePaySign(orderId, price, result) {
    const {
      userModel: { userInfo },
    } = this.props;
    let { data } = await $Req({
      type: "post",
      url: `/pay/pay?userId=${userInfo.userId}&orderId=${orderId}&amount=${price * 100}&orderType=${1}&payModel=MIC_DISTR_PAY_MODEL_NATIVE&payType=MIC_DISTR_PAY_TYPE_ALIPAY`,
    });
    if (!data) return;

    this.setState({
      showAliPayModel: true
    }, () => {
      QR.draw(data.qrCode, "canvas")

      let Timer = setInterval(() => {
        if (this.state.aliPayOk) {
          clearInterval(Timer);

          Taro.redirectTo({
            url: "/pages/order/success/index?orderDetails=" + JSON.stringify(result),
          });
        } else {
          this.queryPay(orderId, data.checkoutId, price * 100);
        }
      }, 2000)
    })
  }

  // 获取微信支付签名
  async getPaySign(orderId, price, result) {
    const {
      userModel: { userInfo },
    } = this.props;
    let { code, message, data } = await $Req({
      type: "post",
      url: "/pay/pay?" + qs.stringify({
        userId: userInfo.userId,
        openId: userInfo.openId,
        orderId: orderId,
        // amount: 1,
        amount: price * 100,
        orderType: 1,
        payModel: "MIC_DISTR_PAY_MODEL_MINI_APP",
        payType: "MIC_DISTR_PAY_TYPE_WEBCHAT",
      })
    });
    if (!data) return;
    this.payOrder(data, result);
  }

  // 支付
  payOrder(res, result) {
    Taro.requestPayment({
      appId: res.appId,
      timeStamp: res.timeStamp,
      nonceStr: res.nonceStr,
      signType: res.signType,
      package: res.package,
      paySign: res.paySign,
      success(res) {
        Taro.showToast({
          title: "支付成功",
          icon: "none",
          duration: 1000,
        });
        Taro.redirectTo({
          url: "/pages/order/success/index?orderDetails=" + JSON.stringify(result),
        });
      },
      fail(res) {
        Taro.showToast({
          title: "支付失败",
          icon: "none",
          duration: 1000,
        });
      },
    });
  }
  countHandle(index, v) {

    const { discountInfo: { level, discountRate }, switchStatus, jfFlag, orderList, testStatus } = this.state;
    let orderListArr = orderList;
    orderListArr[index].quantity = v;

    let totalM = 0;
    let totalR = 0;
    orderListArr.map((item, index) => {
      if (!item.integralStatus) {
        totalM = NP.plus(totalM, NP.times(item.skuCurrPrice, item.quantity));
      } else {
        totalM += item.skuCurrPrice * item.quantity;
        totalR += item.skuCurrPrice * item.quantity - item.integral * item.quantity
      }
    })
    let totalMC = 0;

    let iss = orderListArr.filter(el => el.integralStatus == 1);

    if (discountRate) {
      totalMC = NP.times(totalM, NP.divide(discountRate, 10));
    }

    console.log(iss.length, switchStatus, totalR);

    this.setState({
      orderList: orderListArr,
      totalMoney: totalM,
      totalMoneyCopy: switchStatus ? totalM : (iss.length ? (!totalR ? totalM : totalR) : totalMC)
    })
  }
  render() {
    const {
      userModel: { userInfo },
      orderAction,
    } = this.props;
    const { discountInfo, switchStatus, jfFlag, jfData, totalMoneyCopy, totalMoney, orderList } = this.state;

    let address = Taro.getStorageSync("address");
    address = address.id ? address : {}

    return (
      <View className="page-order-confirm">
        <View className="at-row">
          <View className="at-col c0" style="padding-bottom: 90px">

            <View className="at-row order-confirm-user" onClick={() => {
              Taro.navigateTo({
                url: "/pages/user/address/index?getAddress=true"
              })
            }}>
              <View className="at-col confirm-user-c0 list-item-box">
                <View className="at-row at-row__align--center">
                  <View className="at-col at-col-2">
                    <AtAvatar circle image={address.userPhoto}></AtAvatar>
                  </View>
                  {
                    address.id ?
                      <View className="at-col at-col-9">
                        <View className="at-row">
                          <View className="at-col">
                            <Text className="user-name">{address.receiverName}</Text>
                            <Text className="user-tel">{address.receiverMobile}</Text>
                          </View>
                        </View>
                        <View className="at-row">
                          <View className="at-col" style="white-space: initial;">
                            <Text className="user-address" style="display:block;">
                              {address.receiverDistrict}{address.receiverAddress}
                            </Text>
                          </View>
                        </View>
                      </View>
                      :
                      "  暂无收货地址，点击去添加"
                  }

                  <View className="at-col at-col-1" style="text-align:right;">
                    <AtIcon
                      value="chevron-right"
                      size="25"
                      color="#000"
                    ></AtIcon>
                  </View>
                </View>
              </View>
            </View>

            {
              this.state.orderList.map((el, index) => (
                <View className="at-row shopping-show-box" key={el.id}>
                  <View className="at-col show-box-c0">
                    <View className="at-row show-box-row">
                      <View className="at-col at-col-3 show-box-col-img">
                        <image className="img-goods" src={el.skuCoversUrl} />
                      </View>
                      <View className="at-col at-col-8 show-box-col-main" style={{ marginLeft: "10px" }}>
                        <View className="at-row">
                          <View className="at-col">
                            <Text className="show-box-title">
                              {el.goodsName}
                            </Text>
                          </View>
                        </View>
                        <View className="at-row">
                          <View className="at-col at-col-10">
                            {/* {el.skuTitleType} ; */}
                            <Text className="show-box-norms" style={{ padding: "2px 4px", backgroundColor: "#F1F1F1", borderRadius: "10px", fontSize: "12px" }}>
                              {el.skuTitle}
                            </Text>
                          </View>
                        </View>
                        <View className="at-row">
                          <View className="at-col at-col-7">
                            <Text className="show-box-price-large">
                              ￥{el.skuCurrPrice}
                            </Text>
                            <Text className="show-box-price-small">{el.skuCurrPrice >= 1 ? ".0" : ""}元{el.vip == 0 ? '/积分' : ''}</Text>
                          </View>
                        </View>
                        {
                          el.integralStatus == 1 ?
                            <View className="at-col at-col-7">
                              <Text style="display:block; font-size:12PX; color: #ccc;">
                                积分商品
                                </Text>
                              <Text style="display:block; font-size:12PX; color: #ccc;">
                                需要{el.integral}积分才可以购买
                                </Text>
                            </View>
                            :
                            null
                        }
                      </View>
                      <View
                        className="at-col"
                        style="padding-top: 20PX;text-align: left;font-size: 12PX;color: #999;"
                      >
                        <Text>x{el.quantity}</Text>
                      </View>
                    </View>
                    <View className="at-row at-row__align--center">
                      <View className="at-col at-col-6" style="text-align:left;">
                        购买数量
                  </View>
                      <View className="at-col at-col-6" style="text-align:right;">
                        <AtInputNumber
                          disabledInput
                          min={1}
                          max={100}
                          step={1}
                          value={el.quantity}
                          onChange={this.countHandle.bind(this, index)}
                        />
                      </View>
                    </View>
                  </View>
                </View>
              ))
            }
            {
              this.state.jfFlag ?
                <View className="at-row" style="margin-bottom:10PX;">
                  <View className="at-col list-item-box">
                    <View className="at-row at-row__align--center">
                      <View className="at-col at-col-8">
                        <Text>使用积分支付</Text>
                        <Text style="color:#999;">(可用{this.state.jfData.integral}积分)</Text>
                      </View>
                      {
                        !this.state.bjfDataTotal.length ?
                          <View className="at-col at-col-4">
                            <AtSwitch
                              border={false}
                              disabled={this.state.testStatus ? true : this.state.jfData.integral ? false : true}
                              checked={!this.state.bjfDataTotal.length ? this.state.testStatus : this.state.switchStatus}
                              onChange={(v) => {

                                this.setState({
                                  switchStatus: v,
                                  totalMoneyCopy: v ? totalMoney : discountInfo.discountRate ? NP.times(totalMoney, NP.divide(discountInfo.discountRate, 10)) : totalMoney
                                });
                              }}
                            />
                          </View>
                        :
                        null
                      }
                      
                    </View>
                  </View>
                </View> : null
            }
            {
              discountInfo.level != 0 ?
                <View className="vipHint">您是{discountInfo.level == 1 ? 'VIP' : '分销'}会员，购买商品非积分支付可享受{discountInfo.discountRate}折</View> : null
            }
          </View>
        </View>
        <View className="at-row bottom-row">
          <View className="at-col at-col-all">
            <View className="at-row at-row__justify--between at-row__align--center">
              <View className="at-col at-col-9">
                <Text style="color:#999;font-size:12PX;margin-right:15PX">
                  共{this.state.totalProduct}件商品
                </Text>
                <Text style="color:#1A1A1A;font-size:14PX;">合计:</Text>
                <Text style="color:#1A1A1A;font-size:16PX;">
                  ￥{totalMoneyCopy}
                </Text>
              </View>
              <View className="at-col at-col-3">
                <AtButton
                  circle
                  type="primary"
                  className="btn-submit"
                  onClick={() => {
                    let totalfen = 0;
                    let ingegFlag = this.state.orderList.filter(el => el.integralStatus == 1);
                    this.state.orderList.forEach(el => totalfen += el.integral);

                    if (ingegFlag.length) {
                      for (let i = 0; i < this.state.orderList.length; i++) {
                        let el = this.state.orderList[i];
                        if (this.state.orderList.length > 1) {
                          
                          if (this.state.orderList.length == ingegFlag.length) {

                            if (this.state.jfData.integral < totalfen ) {
                              Taro.showToast({
                                title: "很抱歉！您的积分数过低，不可购买该商品",
                                icon: "none"
                              })
                              return false;
                            }

                            this.setState({
                              showPayModel: true
                            })
                            return false;
                          } else {
                            if (el.integralStatus) {
                              Taro.showToast({
                                title: "很抱歉！积分商品和普通商品不能同时下单，请拆分下单",
                                icon: "none"
                              })
                              return false;
                            }
                          }
                        } else {
                          if (this.state.jfData.integral < totalfen ) {
                            Taro.showToast({
                              title: "很抱歉！您的积分数过低，不可购买该商品",
                              icon: "none"
                            })
                            return false;
                          }

                          this.setState({
                            showPayModel: true
                          })
                          return false;
                        }
                      }
                    } else {
                      this.setState({
                        showPayModel: true
                      })
                      return false;
                    }
                  }}
                >
                  提交订单
                </AtButton>
              </View>
            </View>
          </View>
        </View>
        {/* 支付model */}
        <AtActionSheet isOpened={this.state.showPayModel} cancelText='取消' title='支付类型'
          onCancel={() => {
            this.setState({
              showPayModel: false
            })
          }}
          onClose={() => {
            this.setState({
              showPayModel: false
            })
          }}
        >
          {
            !this.state.switchStatus && this.state.totalMoney > this.state.totalMoneyCopy || !this.state.jfProduct.length ?
              <View>
                <AtActionSheetItem onClick={
                  () => {
                    this.setState({
                      payType: 1,
                      showPayModel: false
                    }, () => {
                      this.buyGoods();
                    })
                  }
                }>
                  微信支付
                </AtActionSheetItem>
                <AtActionSheetItem onClick={
                  () => {
                    this.setState({
                      payType: 3,
                      showPayModel: false
                    }, () => {
                      this.buyGoods();
                    })
                  }
                }>
                  扫码支付
                </AtActionSheetItem>
                <AtActionSheetItem onClick={
                  () => {
                    this.setState({
                      payType: 10,
                      showPayModel: false
                    }, () => {
                      this.buyGoods();
                    })
                  }
                }>
                  收益支付
                </AtActionSheetItem>
              </View>
              :
              null
          }
          {
            this.state.switchStatus && this.state.jfData.integral >= this.state.totalMoney || (this.state.totalMoney <= this.state.totalMoneyCopy && this.state.jfProduct.length) ?
              <AtActionSheetItem onClick={
                () => {
                  this.setState({
                    payType: 2,
                    showPayModel: false
                  }, () => {
                    this.buyGoods();
                  })
                }
              }>
                积分支付
              </AtActionSheetItem>
              :
              null
          }
        </AtActionSheet>

        {/* 支付宝支付 */}
        <AtModal isOpened={this.state.showAliPayModel}>
          <AtModalHeader>扫码支付</AtModalHeader>
          <AtModalContent>
            {
              this.state.showAliPayModel ?
                <canvas style="margin-left: -24px;" id="canvas" canvas-id="canvas"></canvas>
                :
                null
            }

          </AtModalContent>
          <AtModalAction><Button onClick={
            () => {
              this.setState({
                showAliPayModel: false
              })
            }
          }>确定</Button></AtModalAction>
        </AtModal>

      </View>
    );
  }
}
